<template>
  <div v-if="editOpen" style="width: 100%;">
    <t-dialog
      header="新增年度社会、经济效益"
      :visible.sync="dialogOpen"
      :onClose="onClose"
      width="60%"
      :closeOnOverlayClick="false"
      top="5%"
      @confirm="onSubmit"
      :confirmBtn="{
        content: loading?'提交中...':'确认',
        theme: 'primary',
        loading: loading,
      }"
    >
      <div style="height: 65vh">
        <t-form ref="form" resetType="initial"  :colon="true" :data="formData" labelWidth="140px" :rules="rules">
<!--          <t-form-item label="序号" name="sort">-->
<!--            <t-input-number style="width: 390px" clearable v-model="formData.sort" :min="1" placeholder="请输入"></t-input-number>-->
<!--          </t-form-item>-->
          <t-form-item label="年度" name="year">
            <t-date-picker style="width: 390px" mode="year" clearable v-model="formData.year"></t-date-picker>
          </t-form-item>
          <t-form-item label="直接经济效益" name="zjEconomicBenefit">
            <t-input-adornment append="万元">
              <t-input-number :decimal-places="2"
                              @keyup="()=>{if(formData.zjEconomicBenefit){formData.zjEconomicBenefit=Number((formData.zjEconomicBenefit || 0).toString().match(/^\d+(?:\.\d{0,2})?/))}}"
                              :allowInputOverLimit="false" clearable style="width: calc(390px - 45px)"
                              v-model="formData.zjEconomicBenefit"
                              theme="normal"
                              :min="0"></t-input-number>
            </t-input-adornment>
          </t-form-item>
          <t-form-item label="间接经济效益" name="jjEconomicBenefit">
            <t-input-adornment append="万元">
              <t-input-number :decimal-places="2"
                              @keyup="()=>{if(formData.jjEconomicBenefit){formData.jjEconomicBenefit=Number((formData.jjEconomicBenefit || 0).toString().match(/^\d+(?:\.\d{0,2})?/))}}"
                              :allowInputOverLimit="false" clearable style="width: calc(390px - 45px)"
                              v-model="formData.jjEconomicBenefit"
                              theme="normal"
                              :min="0"></t-input-number>
            </t-input-adornment>
          </t-form-item>
          <t-form-item label="社会效益概述" name="socialBenefitContent">
            <t-textarea :autosize="{minRows: 5}"
                        v-model="formData.socialBenefitContent"  placeholder="请输入内容"/>
            <!--             <tiny-mce-editor key="socialBenefitContent" v-model="formData.socialBenefitContent"></tiny-mce-editor>-->
          </t-form-item>
          <t-form-item label="经济效益概述" name="economicBenefitContent">
            <t-textarea :autosize="{minRows: 5}"
                        v-model="formData.economicBenefitContent"  placeholder="请输入内容"/>
            <!--             <tiny-mce-editor key="economicBenefitContent" v-model="formData.economicBenefitContent"></tiny-mce-editor>-->
          </t-form-item>
        </t-form>
      </div>
<!--      <template #footer>-->
<!--        <t-button theme="default" @click="onClose">取消</t-button>-->
<!--        <t-button theme="primary" @click="onSubmit(1)">保存</t-button>-->
<!--        <t-button theme="primary" @click="onSubmit(2)">保存并继续添加</t-button>-->
<!--      </template>-->
    </t-dialog>
   <div style="height: 65vh">
     <div  v-if="isMyProject" class="btn-group-inline">
       <t-button variant="outline" theme="primary" @click="rowIndex=null;formData.sort=data.length+1;title='新增年度社会、经济效益';dialogOpen=true;">
         <t-icon name="add" slot="icon"/>
         新增
       </t-button>
     </div>
        <t-table size="small" :loading="dataLoading" :selected-row-keys="selectedRowKeys"
                 @select-change="(val)=>{selectedRowKeys=val}" rowKey="id" :data="data" :columns="isMyProject?columns:columns3">
          <template #index="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
          <template #zjEconomicBenefit="{row}">
            {{ row.zjEconomicBenefit }}万元
          </template>
          <template #jjEconomicBenefit="{row}">
            {{ row.zjEconomicBenefit }}万元
          </template>
          <template #op="{row}">
            <t-button @click="updateData(row.id)" size="small" variant="text" class="t-button-link">
              <t-icon name="edit-1" slot="icon"/>
              修改
            </t-button>
            <t-button
              @click="handleDelete(row)"
              theme="danger"
              size="small"
              variant="text" class="t-button-link">
              <t-icon name="delete" slot="icon"/>
              删除
            </t-button>
          </template>
          <!--          <template #socialBenefitContent="{row}">-->
          <!--            <div v-html="row.socialBenefitContent"></div>-->
          <!--          </template>-->
          <!--          <template #economicBenefitContent="{row}">-->
          <!--            <div v-html="row.economicBenefitContent"></div>-->
          <!--          </template>-->
        </t-table>
     </div>
  </div>
  <div v-else style="width: 100%;">
        <t-dialog
          :header="header"
          :visible.sync="visible"
          :onClose="closeDialog"
          width="80%"
          :closeOnOverlayClick="false"
          :confirm-btn="null"
          top="5%"
        >
          <div style="height: 65vh;">
            <t-table :loading="dataLoading" size="small" rowKey="id" :data="data" :columns="columns2">
              <template #index="{ rowIndex }">
                {{ rowIndex + 1 }}
              </template>
              <template #zjEconomicBenefit="{row}">
                {{ row.zjEconomicBenefit }}万元
              </template>
              <template #jjEconomicBenefit="{row}">
                {{ row.zjEconomicBenefit }}万元
              </template>
              <!--          <template #socialBenefitContent="{row}">-->
              <!--            <div v-html="row.socialBenefitContent"></div>-->
              <!--          </template>-->
              <!--          <template #economicBenefitContent="{row}">-->
              <!--            <div v-html="row.economicBenefitContent"></div>-->
              <!--          </template>-->
            </t-table>
          </div>
        </t-dialog>
  </div>
</template>

<script>

export default {
  name: "project-benefit",
  components: {
  },
  props: {
    value: Array,
    header: {
      type: String,
    },
    objId: [String, Number],
    editOpen: {
      type: Boolean,
      default: false
    },
    projectName: {
      type: String,
    }
  },
  data() {
    return {
      isMyProject: false,
      rowIndex: null,
      formData:{
        sort: 1,
        year: '',
        zjEconomicBenefit: null,
        jjEconomicBenefit: null,
        socialBenefitContent: '',
        economicBenefitContent: '',
        serviceCode: 'kjxm',
        serviceName: '科技项目',
        businessId: this.objId,
        businessName: this.projectName,
      },
      rules: {
        year: [
          {
            required: true,
            message: "年度不能为空",
          }
        ],
        zjEconomicBenefit: [
          {
            required: true,
            message: "直接经济效益不能为空",
          }
        ],
        jjEconomicBenefit: [
          {
            required: true,
            message: "直接经济效益不能为空",
          }
        ],
      },
      title: '',
      dialogOpen: false,
      loading: false,
      visible: true,
      companyLoading: false,
      companyOptions: [],
      dataLoading: false,
      deptMenuOptions: [],
      selectedRowKeys: [],
      data: [],
      columns: [
        // {
        //   colKey: 'row-select',
        //   type: 'single',
        //   title: "选择",
        //   width: 64
        // },
        // {
        //   colKey: 'index',
        //   title: "序号",
        //   align: "center",
        //   width: 64
        // },
        {
          colKey: "year",
          title: "年度",
          align: "center",
          width: 100
        },
        {
          colKey: "zjEconomicBenefit",
          title: "直接经济效益",
          align: "center",
          width: 120
        },
        {
          colKey: "jjEconomicBenefit",
          title: "间接经济效益",
          align: "center",
          width: 120
        },
        {
          colKey: "socialBenefitContent",
          title: "社会效益概述",
          align: "center",
        },
        {
          colKey: "economicBenefitContent",
          title: "经济效益概述",
          align: "center",
        },
        {
          colKey: "op",
          title: "操作",
          align: "center",
        },
      ],
      columns2: [
        // {
        //   colKey: 'index',
        //   title: "序号",
        //   align: "center",
        //   width: 64
        // },
        {
          colKey: "year",
          title: "年度",
          align: "center",
        },
        {
          colKey: "zjEconomicBenefit",
          title: "直接经济效益",
          align: "center",
        },
        {
          colKey: "jjEconomicBenefit",
          title: "间接经济效益",
          align: "center",
        },
        {
          colKey: "socialBenefitContent",
          title: "社会效益概述",
          align: "center",
        },
        {
          colKey: "economicBenefitContent",
          title: "经济效益概述",
          align: "center",
        },
      ],
      columns3: [
        // {
        //   colKey: 'index',
        //   title: "序号",
        //   align: "center",
        //   width: 64
        // },
        {
          colKey: "year",
          title: "年度",
          align: "center",
        },
        {
          colKey: "zjEconomicBenefit",
          title: "直接经济效益",
          align: "center",
        },
        {
          colKey: "jjEconomicBenefit",
          title: "间接经济效益",
          align: "center",
        },
        {
          colKey: "socialBenefitContent",
          title: "社会效益概述",
          align: "center",
        },
        {
          colKey: "economicBenefitContent",
          title: "经济效益概述",
          align: "center",
        },
        // {
        //   colKey: "op",
        //   title: "操作",
        //   align: "center",
        // },
      ],
    }
  },
  watch: {
    objId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getBenefitList(val);
        }
      }
    },
    data: {
      deep: true,
      immediate: true,
      handler(val) {
        const newData = this.data.map((val, index) => ({...val, sort: index + 1}))
        this.$emit("input", newData);
      }
    },
  },
  created() {
    this.$api.kjxm.project.get(this.objId).then(response => {
      if (response.data.createUserId === Number(this.$store.state.user.userId)) {
        this.isMyProject = true;
      }
    }).catch((e) => {
      this.$message.error(e.toString());
    });
  },
  methods: {
    onSubmit(){
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.loading = true;
          if(this.formData.id){
            this.$api.cgzh.benefitUpdate(this.formData).then(response => {
              this.$message.success("修改成功");
              this.$refs.form.reset();
              this.getBenefitList();
              this.dialogOpen = false;
              this.loading = false;
            }).catch((e) => {
              this.loading = false;
              this.$message.error(e.toString());
            });
          }else {
            this.$api.cgzh.benefitAdd(this.formData).then(response => {
              this.$message.success("新增成功");
              this.$refs.form.reset();
              this.getBenefitList();
              this.dialogOpen = false;
              this.loading = false;
            }).catch((e) => {
              this.loading = false;
              this.$message.error(e.toString());
            });
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
    closeDialog() {
      this.$emit("update:visible", false);
    },
    onClose() {
      this.dialogOpen = false;
    },
    handleDelete(row){
      const confirmDia = this.$dialog.confirm({
        header:"系统提示",
        body:`是否确认删除年度为"${row.year}"的数据项？`,
        theme: "warning",
        onConfirm: () => {
          this.$api.cgzh.benefitDel(row.id).then(
            () => {
              this.$message.success("删除成功");
              this.getBenefitList();
              // 请求成功后，销毁弹框
              confirmDia.destroy();
            }
          ).catch((e) => {
            this.$message.error(e.toString());
          });
        },
      })
    },
    updateData(id){
      this.$api.cgzh.benefitGet(id).then(response => {
        Object.assign(this.formData, response.data);
        this.dialogOpen = true;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getBenefitList() {
      if (this.objId) {
        this.dataLoading = true;
        this.$api.cgzh.benefitListGet('kjxm',this.objId).then(response => {
          this.data = response.data;
          this.dataLoading = false;
        }).catch((e) => {
          this.dataLoading = false;
          this.$message.error(e.toString());
        });
      }
    },
  }
}
</script>

<style lang="less" scoped>
.step-form {
  padding: 0 24px;
}
.t-form__item {
  margin-bottom: var(--td-comp-margin-xxl);
}
.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}
</style>
